﻿namespace Dcms.Common
{
    using System;
    using System.Security.Cryptography;
    using System.Text;

    public class AES
    {
        private static byte[] Keys = new byte[] { 0x41, 0x72, 0x65, 0x79, 0x6f, 0x75, 0x6d, 0x79, 0x53, 110, 0x6f, 0x77, 0x6d, 0x61, 110, 0x3f };

        public static string Decode(string decryptString, string decryptKey)
        {
            try
            {
                decryptKey = Dcms.Common.Utils.GetSubString(decryptKey, 0x20, "");
                decryptKey = decryptKey.PadRight(0x20, ' ');
                RijndaelManaged rijndaelProvider = new RijndaelManaged();
                rijndaelProvider.Key = Encoding.UTF8.GetBytes(decryptKey);
                rijndaelProvider.IV = Keys;
                ICryptoTransform rijndaelDecrypt = rijndaelProvider.CreateDecryptor();
                byte[] inputData = Convert.FromBase64String(decryptString);
                byte[] decryptedData = rijndaelDecrypt.TransformFinalBlock(inputData, 0, inputData.Length);
                return Encoding.UTF8.GetString(decryptedData);
            }
            catch
            {
                return "";
            }
        }

        public static string Encode(string encryptString, string encryptKey)
        {
            encryptKey = Dcms.Common.Utils.GetSubString(encryptKey, 0x20, "");
            encryptKey = encryptKey.PadRight(0x20, ' ');
            RijndaelManaged rijndaelProvider = new RijndaelManaged();
            rijndaelProvider.Key = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 0x20));
            rijndaelProvider.IV = Keys;
            ICryptoTransform rijndaelEncrypt = rijndaelProvider.CreateEncryptor();
            byte[] inputData = Encoding.UTF8.GetBytes(encryptString);
            return Convert.ToBase64String(rijndaelEncrypt.TransformFinalBlock(inputData, 0, inputData.Length));
        }
    }
}

